package com.bw.im.msg

import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import com.bw.common.mvi.BaseFragment
import com.bw.im.databinding.ActivityMsgBinding
import com.bw.widget.decoration.MsgDecoration
import com.bw.widget.header.MDMRefreshHeader
import com.scwang.smart.refresh.footer.ClassicsFooter
import kotlinx.coroutines.launch

class MsgFragment : BaseFragment<ActivityMsgBinding,MsgViewModel>() {

    private val msgAdapter : MsgAdapter by lazy { MsgAdapter() }

    override fun createVM(): MsgViewModel {
        return viewModels<MsgViewModel>().value
    }

    override fun initView() {
        v.msgTopPage.backImg.visibility = View.GONE
        v.msgTopPage.titleTv.text = "消息"
        v.msgSmart.setRefreshHeader(MDMRefreshHeader(requireContext(),null))
        v.msgSmart.setRefreshFooter(ClassicsFooter(requireContext()))
        v.msgSmart.setOnRefreshListener { vm.requestRefresh() }
        v.msgSmart.setOnLoadMoreListener { vm.requestLoad() }
        val manager = LinearLayoutManager(requireContext())
        manager.orientation = LinearLayoutManager.VERTICAL
        v.msgRv.layoutManager = manager
        v.msgRv.addItemDecoration(MsgDecoration(requireContext()))
        v.msgRv.adapter = msgAdapter
    }

    override fun initData() {
        vm.requestRefresh()
    }

    override fun bindState() {
        lifecycleScope.launch {
            vm.mutableContainer.uiStateFlow.collect{
                if (it.refreshState){
                    msgAdapter.setNewInstance(it.datas)
                }
                if (it.loadState){
                    msgAdapter.adds(it.datas)
                }
            }
        }
    }

    override fun createViewBinding(): ViewBinding {
        return ActivityMsgBinding.inflate(inflate)
    }
}